const users = require('../models/users.models')
const Joi = require('joi')

/**
 * 创建用户
 * @param req
 * @param res
 */
const createUser = (req, res) => {
  const newUser = req.body

  const schema = Joi.object({
    username: Joi.string()
      .alphanum()
      .min(3)
      .max(10)
      .required(),

    password: Joi.string()
      .pattern(new RegExp('^[a-zA-Z0-9]{3,10}$')).required(),

    repeat_password: Joi.ref('password'),

    email: Joi.string()
      .email({ minDomainSegments: 2, tlds: { allow: ['com', 'net'] } }).required(),
    nickname: Joi.string()
  })
    .with('password', 'repeat_password') //password和repeat_password必须同时存在

  let { error } = schema.validate(newUser)

  if (error) {
    let details = error.details[0]
    let path = details.path[0]

    return res.sendError({ msg: details[Object.keys(details).find(() => details['path'][0] === path)] })
  }

  users.addNewUser(req.body, (error, user_id) => {
    if (error) {
      return res.sendError(error)
    }
    return res.sendSuccess({ user_id }, '添加用户成功')
  })

}

/**
 * 获取全部用户
 * @param req
 * @param res
 */
const getAllUsers = (req, res) => {

  users.getAllUsers((err, allUser) => {
    if (err) {
      return res.status(500).send({ error: 'Internal Server Error' })
    } else {
      const allUserData = allUser.map(item => {
        return {
          user_id: item.user_id,
          email: item.email,
          username: item.username,
          nickname: item.nickname
        }
      })
      return res.sendSuccess(allUserData, '获取用户信息成功')
    }
  })
}

/**
 * 用户登录
 * @param req
 * @param res
 */
const login = (req, res) => {
  let username = req.body.username
  let password = req.body.password

  users.authenticateUser(username, password, (err, id) => {
    if (err === 404) return res.sendError(err, 404)
    if (err) return res.sendError(err)
    users.getToken(id, (err, token) => {
      if (token) {
        return res.sendSuccess({ user_id: id, session_token: token }, '登录成功')
      } else {
        users.setToken(id, (err, token) => {
          if (err) return res.sendError(err)
          return res.sendSuccess({ user_id: id, session_token: token }, '登录成功')
        })
      }
    })
  })
}

/**
 * 用户退出
 * @param req
 * @param res
 * @returns {*}
 */
const logout = (req, res) => {
  let token = req.get('token')
  console.log('token', token)

  // 使用 removeToken 函数移除用户的会话令牌
  if (!token) return res.sendError({ msg: 'token is empty' })
  users.removeToken(token, (err, result) => {
    console.log('err', err)
    if (err) {
      return res.sendError(err)
    }
    return res.sendSuccess(result, '成功删除token')
  })

}

/**
 * 查询单个用户
 * @param req
 * @param res
 */
const getUserById = (req, res) => {
  let user_id = req.params.id
  users.getUserById(user_id, (err, result) => {
    if (err) return res.sendError(err)
    return res.sendSuccess(result, '成功获取用户信息')
  })
}
module.exports = {
  createUser,
  login,
  logout,
  getAllUsers,
  getUserById

}
